package com.naizhuai.network.Repository;

import com.naizhuai.network.exception.ExceptionEngine;
import com.naizhuai.network.exception.ServerException;
import android.content.Context;

import com.google.gson.Gson;

import okhttp3.RequestBody;
import rx.Observable;
import rx.functions.Func1;

/**
 * Created by lichenxi on 2017/5/15.
 */
public class DataApiStoreIml implements DataApiStore {
    private Api serviceApi;
    private static DataApiStoreIml INSTANCE=null;
     public static DataApiStore getInstance(Context context){
         if (INSTANCE==null){
             INSTANCE=new DataApiStoreIml(context);
         }
         return INSTANCE;
     }

    private DataApiStoreIml(Context context) {
//        serviceApi= RetrofitFactory.getInstance(context).create(Api.class);

    }

    @Override
    public Observable<?> login(String region, String phone, String password) {
         return null;
//        return  serviceApi.login(getRequestBody(new Login.LoginRequest(region,phone,password)))
//                                  .map(new ServerResultFunc<Login.LoginResponse>())
//                                  .onErrorResumeNext(new HttpResultFunc<Login.LoginResponse>());

    }



    private RequestBody getRequestBody(Object obj) {
        String route = new Gson().toJson(obj);
        RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),route);
        return body;
    }

    private class ServerResultFunc<T> implements Func1<Result<T>, T> {
        @Override
        public T call(Result<T> httpResult) {
            if (httpResult.code != 200) {
                throw new ServerException(httpResult.code);
            }
            return httpResult.result;
        }
    }

    private class HttpResultFunc<T> implements Func1<Throwable, Observable<T>> {
        @Override
        public Observable<T> call(Throwable throwable) {
            return Observable.error(ExceptionEngine.handleException(throwable));
        }
    }
}
